package cn.com.callback

import groovy.json.*;
import groovy.swing.impl.DefaultAction
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.crypto.Cipher
import javax.crypto.SecretKey
import javax.crypto.spec.SecretKeySpec
import javax.servlet.RequestDispatcher;
import cn.com.callback.CallBackInvoke
import cn.com.callback.ServiceBackInvoke
import cn.com.elite.EliteBean;
import cn.com.elite.Util;
import java.security.MessageDigest;
import java.sql.ResultSet;
import java.text.ParseException
import java.text.SimpleDateFormat;
import java.time.Instant

import org.apache.commons.codec.binary.Base64
import org.apache.commons.codec.digest.DigestUtils
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import cn.com.kh.hst.ThreeDesUtil
import cn.com.kh.KHUtil;
import cn.com.kh.getProperty;


/**
 *
 * @Title: aipHSTCounselor
 * @Description:华盛证券 服务顾问列表查询 --内部接口
 * @author: TH
 * @date 2021-07-07 17:42:00
 *
 */

public class aipHSTCounselor implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(aipHSTCounselor.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        response.setCharacterEncoding("UTF-8");
        response.setHeader("Access-Control-Allow-Origin", "*");
        String getMethod = request.getMethod();
        log.debug("getMethod:" + getMethod);

        String inData = "";
        String outData = "";
        String totalData = "";
        String dataSourceID = "dataSource";


        BufferedReader iny = null;
        if (getMethod.equals("GET")) {
            inData = request.getParameter("data");
            log.debug("原始Get请求参数:" + inData);
        } else {
            InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
            iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                inData += line;
            }
            log.debug("原始Post请求参数:" + inData);
        }

        inData = URLDecoder.decode(inData, "UTF-8");
        log.debug("原始inData URLDecoder:" + inData);

        try {

            long startTime = System.currentTimeMillis();
            String reJson = null;
            long endTime = 0;

            //鉴权变量
            String appid = getProperty.get("appid");
            String appsecret = getProperty.get("appsecret");

            //sign加密前后
            String signfront = "";
            String signafter = "";

            String sign_time=Instant.now().getEpochSecond();
            log.debug("解析信息-" +  "sign_time: " + sign_time);

            def pageNo = "1";
            def pageSize = "20";

            HashMap<String, String> paramHashMap = new HashMap<String, String>() {
                {
                    put("sign_time", sign_time);
                    put("pageNo", pageNo);
                    put("pageSize", pageSize);
                }
            };

            log.debug("paramHashMap：" + paramHashMap);
            //自然排序 升序参数
            signfront= ThreeDesUtil.sortMap(paramHashMap,appid,appsecret);
            log.debug("sign加密MD5前：" + signfront);
            signafter = Util.getMD5Str(signfront);
            log.debug("sign加密MD5后：" + signafter);

            //拼接接口入参
            paramHashMap.put("client_key", appid);
            paramHashMap.put("sign", signafter);

            String injson=ThreeDesUtil.SplicingMap(paramHashMap,"&");
            log.debug("injson:" + injson);

            String[] GDSQL = new String[3];
            GDSQL[0] = "DELETE FROM hst_counselor_list_his where synchroDate<= DATE_SUB(CURDATE(), INTERVAL 30 DAY)  ";
            GDSQL[1] = "Insert into hst_counselor_list_his select * from hst_counselor_list where synchroDate<str_to_date(DATE_FORMAT(NOW(),'%Y-%m-%d'),'%Y-%m-%d %H:%i:%s')";
            GDSQL[2] = "delete from hst_counselor_list where synchroDate<str_to_date(DATE_FORMAT(NOW(),'%Y-%m-%d'),'%Y-%m-%d %H:%i:%s')";
            def GDresult = eliteBean.updateBatch(GDSQL, "dataSource");

            totalData = Querypromocode(eliteBean, injson,dataSourceID);
            //解析SSO返回信息
            JSONObject jsonObject = new JSONObject(totalData);
            String total = GetJV(jsonObject, "message");
            log.debug("total:" + total);
            double number=Integer.parseInt(total)/Integer.parseInt(pageSize);
            log.debug("number :" + number);
            int count=Math.ceil(number);
            log.debug("count :" + count);

            for (int i = 2; i <=count; i++) {
				//华盛接口连续调用可能异常 添加2S睡眠
				Thread.sleep(2 * 1000);
				pageNo=String.valueOf(i);
				log.debug("pageNo :" + pageNo);
				sign_time=Instant.now().getEpochSecond();
                HashMap<String, String> paramHashMap1 = new HashMap<String, String>() {
                    {
                        put("sign_time", sign_time);
                        put("pageNo", pageNo);
                        put("pageSize", pageSize);
                    }
                };

                log.debug("paramHashMap1：" + paramHashMap1);
                //自然排序 升序参数
                signfront= ThreeDesUtil.sortMap(paramHashMap1,appid,appsecret);
                log.debug("sign加密MD5前：" + signfront);
                signafter = Util.getMD5Str(signfront);
                log.debug("sign加密MD5后：" + signafter);

                //拼接接口入参
                paramHashMap1.put("client_key", appid);
                paramHashMap1.put("sign", signafter);

                String injson1=ThreeDesUtil.SplicingMap(paramHashMap1,"&");
                log.debug("injson1:" + injson1);

                Querypromocode(eliteBean, injson1,dataSourceID);
            }
            outData = "{\"result\":\"1\",\"message\":\"处理成功\",\"data\":[]}";


        } catch (Exception e) {
            log.error("接口处理异常" + e.getMessage());
            // 失败返回
            outData = "{\"result\":\"-1\",\"message\":\"处理失败(" + e.getMessage() + ")\",\"data\":[]}";
        }

        return outData;
    }

    //
    public static String Querypromocode(EliteBean eliteBean , String injson, String dataSourceID) {

        long startTime = System.currentTimeMillis();
        log.debug("处理开始时间:" + startTime);

        long endTime = System.currentTimeMillis();

        String reJson = null;
        try {

            String doURL = getProperty.get("HSTURL");
            doURL = doURL+"/ae/query-page";
            log.debug("doURL:" + doURL);
            Map<String, String> headMap = new HashMap<String, String>();
            headMap.put("Content-Type", "application/x-www-form-urlencoded");
            def getResult = Util.doHttpPostUseHead(doURL, injson, "UTF-8", 10000, 0, headMap);
            log.debug("getResult:" + getResult);
            UUID uuid = UUID.randomUUID();

            //解析SSO返回信息
            JSONObject jsonObject = new JSONObject(getResult);
            String code = GetJV(jsonObject, "code");
            String result = GetJV(jsonObject, "result");
            JSONObject dataObject;

            log.debug("code:" + code);
            if(code == "00000") {
                dataObject = new JSONObject(result);
                String rows = GetJV(dataObject, "rows");
                String total = GetJV(dataObject, "total");
                log.debug('rows'+rows);
                log.debug('total'+total);

                SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String dateStr = dateformat.format(System.currentTimeMillis());

                JSONArray arrJsonArray = new JSONArray(rows);
                int arrInt = arrJsonArray.length();
                for (int i = 0; i < arrInt; i++) {
                    JSONObject arrSmsJson = arrJsonArray.getJSONObject(i);
                    String id =GetJV(arrSmsJson,"id");//服务顾问ID
                    String name=GetJV(arrSmsJson,"name");//服务顾问姓名
                    String nickname =GetJV(arrSmsJson,"nickname");//昵称
                    String  mobile =GetJV(arrSmsJson,"mobile");//手机号
                    String email =GetJV(arrSmsJson,"email");//邮箱
                    String departmentName =GetJV(arrSmsJson,"departmentName");//部门名称
                    String status=GetJV(arrSmsJson,"status");//状态
                    String remark =GetJV(arrSmsJson,"remark");//备注
                    String groupType =GetJV(arrSmsJson,"groupType");//分组
                    String qrCodePath =GetJV(arrSmsJson,"qrCodePath");//企业微信二维码
                    String createdBy =GetJV(arrSmsJson,"createdBy");//创建人
                    String updatedBy =GetJV(arrSmsJson,"updatedBy");//更新人
                    String createdDate =GetJV(arrSmsJson,"createdDate");//创建时间
                    String updatedDate =GetJV(arrSmsJson,"updatedDate");//更新人

                    log.debug(name + ":name");
                    log.debug(id + ":id");
                    def dataresult = eliteBean.update(
                            "insert into hst_counselor_list(counselor_id,name,nickname,mobile,email,departmentName,status,remark,groupType,qrCodePath,createdBy,updatedBy,createdDate,updatedDate,batch_id,insertDate,synchroDate)values ('"+id+"','"+name+"','"+nickname+"','"+mobile+"','"+email+"','"+departmentName+"','"+status+"','"+remark+"','"+groupType+"','"+qrCodePath+"','"+createdBy+"','"+updatedBy+"','"+createdDate+"','"+updatedDate+"','"+uuid+"','"+dateStr+"',now())", "dataSource");

                }

                reJson = "{\"result\":\"1\",\"message\":"+total+"}";

            }else {
                String msg = GetJV(jsonObject, "msg");
                reJson = "{\"result\":\"-1\",\"message\":\"用户获取失败(" + msg + ")\"}";
            }

        } catch (Exception e) {
            log.error("接口处理异常" + e.getMessage());
            // 失败返回
            reJson = "{\"result\":\"-1\",\"message\":\"接口异常\"}";
        }
        return reJson;
    }


    // 解析Json值
    public static String GetJV(JSONObject inJson, String getKey) {
        String Rev_Value = null;
        try {
            Rev_Value = inJson.getString(getKey);
        } catch (Exception e) {
            try {
                Rev_Value = String.valueOf(inJson.getInt(getKey));
            } catch (Exception e1) {
                try {
                    Rev_Value = String.valueOf(inJson.getJSONArray(getKey));
                } catch (Exception e2) {
                    try {
                        Rev_Value = String.valueOf(inJson.getJSONObject(getKey));
                    } catch (Exception e3) {
                        Rev_Value = "";
                    }
                }
            }
        } finally {
            if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
                Rev_Value = "";
            } else {
            }
        }
        log.debug("解析-k=" + getKey + " v=" + Rev_Value);
        return Rev_Value;
    }


    // 非空校验isNull
    public static boolean isNull(String value) {

        boolean reFlag = true;
        if (value == "" || value.length() <= 0) {
            reFlag = true;
        } else {
            reFlag = false;
        }
        log.debug(reFlag);
        return reFlag;
    }

    // 非空校验isNullMSG
    public static String isNullMSG(String key, String value) {

        String reResult = "";
        if (value == "" || value.length() <= 0) {
            reResult = key + "必填字段;";
        }
        return reResult;
    }

}
